<template>
  <div class="user-manage">
    <div class="manage-btns">
      <el-button size="small" type="primary" @click="openDialog('create', null)">新增用户</el-button>
    </div>
    <div class="manage-list">
      <el-table :data="userList.tabData" border>
        <el-table-column prop="name" label="用户名"> </el-table-column>
        <el-table-column prop="phone" label="手机号"> </el-table-column>
        <el-table-column prop="typeName" label="用户身份"> </el-table-column>
        <el-table-column prop="companyName" label="所属公证处"> </el-table-column>
        <el-table-column prop="idCard" label="身份证号"> </el-table-column>
        <el-table-column prop="createTime" label="注册时间"> </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录时间"> </el-table-column>
        <el-table-column align="center" width="200px" label="操作">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openDialog('update', scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="delUserFun(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog :width="500" :destroy-on-close='true' :title="userModel.dialogTit" v-model="userModel.modelVisible">
      <el-form label-position="left" class="edite-user-form">
        <el-form-item label="姓名" label-width="90px">
          <el-input size="small" v-model="userModel.userInfo.name"></el-input>
        </el-form-item>
        <el-form-item label="身份证" label-width="90px">
          <el-input size="small" v-model="userModel.userInfo.idCard"></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="90px">
          <el-input size="small" v-model="userModel.userInfo.phone"></el-input>
        </el-form-item>
        <el-form-item label="所属公证处" label-width="90px">
          <company-choose @selected='companySelected' :defaultVal='userModel.status === "update" ? userModel.userInfo.company : ""' ></company-choose>
        </el-form-item>
        <el-form-item label="所属身份" label-width="90px">
          <usertype-choose :defaultVal='userModel.userInfo.type' purpose='IsManage' @change='usertypeChange'></usertype-choose>
        </el-form-item>
        <el-form-item label="监管区域" label-width="90px" v-if='userModel.userInfo.type === 4'>
          <ul v-if="userModel.status === 'update'">
            <li v-for="item in userModel.userInfo.power" :key="item.id">{{item.region}}</li>
          </ul>
          <div class="city-choose-item" v-for="(item, key) in userModel.userInfo.power" :key="item.id">
            <CityChoose
              :checkStrictly='true'
              :defaultCitys='[item.provinceID, item.cityID, item.countyID]'
              @inputValue="(value) => setSupervisionCityInput(key, value)"
              @selected='(data) => supervisionCity(key, data)'>
            </CityChoose>
            <i v-if="key === 0" class="push-city el-icon-circle-plus" @click="handUserInfoPower('push', key)"></i>
            <i v-else class="remove-city el-icon-remove" @click="handUserInfoPower('remove', key)"></i>
          </div>
        </el-form-item>
        <el-form-item label="初始密码" label-width="90px" v-if="userModel.status === 'create'">
          <el-input size="small" v-model="userModel.addUserPassword"></el-input>
        </el-form-item>
        <el-form-item label-width="90px" class="edit-dialog-btn">
          <el-button size="small" type="primary" @click="summit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref, reactive, toRaw } from 'vue';
import { ElMessageBox } from 'element-plus';
import { useStore } from 'vuex';
import { CompanyChoose, UsertypeChoose, CityChoose} from '@/components';
import { nanoid } from 'nanoid';
export default defineComponent({
  name: 'userManage',
  components: { CompanyChoose, UsertypeChoose, CityChoose },
  setup() {
    const store = useStore();
    // 监管员默认选择城市模板
    const defaultPower = [
      {
        id: nanoid(),
        provinceID: "",
        cityID: "",
        countyID: "",
        region: ""
      }
    ];
    const userModel = reactive({
      status: '',
      dialogTit: '',
      modelVisible: false,
      addUserPassword: '',
      updateUserId: '',
      userInfo: {
        name: '',
        type: 0,
        idCard: '',
        phone: '',
        company: '',
        power: []
      },
    });
    const userList = reactive({
      tabData: [],
    });
    const resetUserInfo = () => {
      Object.keys(userModel.userInfo).forEach(item => userModel.userInfo[item] = '');
      userModel.userInfo.power = defaultPower;
      userModel.updateUserId = '';
    };
    const openDialog = (type:string, data:any) => {
      resetUserInfo();
      const types = {
        create: '新增用户',
        update: '编辑用户'
      };
      userModel.status = type;
      userModel.dialogTit = types[type];
      if (type === 'update') {
        const {id, name, type, idCard, phone, companyID, power } = data;
        userModel.updateUserId = id;
        userModel.userInfo = {
          name,
          type,
          idCard,
          phone,
          company: companyID,
          power: power ? power : defaultPower
        };
      }
      userModel.modelVisible = true;
    };
    // 删除用户
    const delUserFun = async(user) => {
      await ElMessageBox.confirm('确定要删除此用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      await store.dispatch('user/userDetele', { id: user.id });
      await getUserlist();
    };
    // 获取用户列表
    const getUserlist = async () => {
      userList.tabData = await store.dispatch('user/userList');
    };
    // 提交新增/编辑用户
    const summit = async () => {
      const params = userModel.userInfo;
      switch (userModel.status) {
        case 'create':
          await store.dispatch('user/userReg', {
            ...params,
            password: userModel.addUserPassword
          }); 
          break;
        case 'update':
          await store.dispatch('user/userUpdate', {
            id: userModel.updateUserId,
            ...params,
          }); 
          break;
        default:
          break;
      }
      userModel.modelVisible = false;
      getUserlist();
    };
    const companySelected = (data) => {
      userModel.userInfo.company = data;
    };
    const usertypeChange = (data) => {
      userModel.userInfo.type = data;
    };
    const handUserInfoPower = (type, index) => {
      switch (type) {
        case 'push':
          userModel.userInfo.power.push({ ...defaultPower[0], id: nanoid() })
          break;
        case 'remove':
          userModel.userInfo.power.splice(index, 1);
          break;
        default:
          break;
      }
    };
    // 设置城市中文字段
    const setSupervisionCityInput = (key, value) => {
      userModel.userInfo.power[key].region = value;
    };
    // 设置城市省市区字段
    const supervisionCity = (key, data) => {
      const [provinceID, cityID, countyID] = data;
      if (provinceID) {
        userModel.userInfo.power[key].provinceID = provinceID;
      }
      if (cityID) {
        userModel.userInfo.power[key].cityID = cityID;
      }
      if (countyID) {
        userModel.userInfo.power[key].countyID = countyID;
      }
    };
    onMounted(() => {
      getUserlist();
    });
    return {
      userList,
      userModel,
      openDialog,
      delUserFun,
      summit,
      companySelected,
      usertypeChange,
      supervisionCity,
      handUserInfoPower,
      setSupervisionCityInput,
    };
  },
});
</script>
<style lang="scss" scoped>
.user-manage {
  .manage-btns {
    @extend %container;
  }
  .manage-list {
    @extend %container;
    margin-top: 10px;
  }

  .edite-user-form {
    .el-form-item {
      margin-bottom: 10px;
    }
    .edit-dialog-btn {
      text-align: right;
    }
  }
  .city-choose-item {
    display: flex;
    margin-bottom: 5px;
    i {
      font-size: 22px;
      margin-left: 5px;
      line-height: 30px;
      cursor: pointer;
    }
    .push-city {
      color: #67C23A;
    }
    .remove-city {
      color: #F56C6C;
    }
  }
}
</style>
